package com.example.demo2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
public class DBUtil {
	private static Connection cn = null;
	private static String url ="jdbc:mysql://127.0.0.1:3306/gp";
	private static String user ="root";
	private static String password = "123456";
	public static Connection getConnection(){
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			cn = DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cn;
	}
	public static int update(String sql,Vector vc){
		int n=0;
		try {
			cn = DBUtil.getConnection();
			PreparedStatement ps = cn.prepareStatement(sql);
			for(int i=0;i<vc.size();i++){
				ps.setObject(i+1, vc.get(i));
			}
			n= ps.executeUpdate();
			ps.close();
			cn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return n;
	}
	public static ResultSet find(String sql,Vector vc){  //多条件查询
		ResultSet rs = null;
		try {
			cn = DBUtil.getConnection();
			PreparedStatement ps = cn.prepareStatement(sql);
			for(int i=0;i<vc.size();i++){
				ps.setObject(i+1, vc.get(i));
			}
			rs = ps.executeQuery();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rs;
	}
	public static ResultSet findall(String sql){  //多条件查询
		ResultSet rs = null;
		try {
			cn = DBUtil.getConnection();
			PreparedStatement ps = cn.prepareStatement(sql);
			rs = ps.executeQuery();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rs;
	}
	public static ResultSet findById(String sql,int id){  //单条件查询
		ResultSet rs = null;
		try {
			cn = DBUtil.getConnection();
			PreparedStatement ps = cn.prepareStatement(sql);
			ps.setInt(1, id);
			rs = ps.executeQuery();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rs;
	}
	public static void close(){
		try {
			cn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
